import can
import subprocess  
  
def activate_can_interface(interface_name):  
    # 构建命令  
    command = f"sudo ip link set {interface_name} up"  
    # 执行命令  
    result = subprocess.run(command, shell=True, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)  
    # 检查是否有错误输出  
    if result.stderr:  
        print(f"Error activating CAN interface {interface_name}: {result.stderr.decode()}")  
    else:  
        print(f"CAN interface {interface_name} activated successfully.")  
  
# 调用函数激活can0接口  
# activate_can_interface("can0")
# 创建一个CAN总线接口对象
bus = can.interface.Bus(interface='socketcan', channel='can0', bitrate=500000)

# 创建一个CAN消息对象
msg = can.Message(arbitration_id=0x123, data=[0, 1, 2, 3, 4, 5, 6, 7], is_extended_id=False)

# 发送CAN消息
bus.send(msg)

# 接收CAN消息
while True:
    try:
        received_msg = bus.recv()
        print(f"Received CAN message with ID {received_msg.arbitration_id} and data {received_msg.data}")
    except KeyboardInterrupt:
        break